package com.qf.fmcommodity.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.fmcommodity.user.entity.Category;
import com.qf.fmcommodity.user.entity.Product;
import com.qf.fmcommodity.user.entity.ProductImg;
import com.qf.fmcommodity.user.mapper.CategoryMapper;
import com.qf.fmcommodity.user.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.fmcommodity.user.service.IProductImgService;
import com.qf.fmcommodity.user.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品分类 服务实现类
 * </p>
 *
 * @author 苇名一心
 * @since 2023-02-13
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    IProductService iProductService;

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    IProductImgService iProductImgService;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<Category> getAll() {

      /*  //查询所以有一级分类
        List<Category> list = categoryMapper.selectAll();

        //
        List<Category> list1 =  organiezCategory(0,list);
        return list1;*/
        //查询所有1级分类信息
        List<Category> firstCategoryList = list(new QueryWrapper<Category>().eq("parent_id", 0));
        //遍历所有查询的一级分类，填充二级分类
        for (Category category : firstCategoryList) {
            //获取当前一级分类ID
            Integer categoryId = category.getCategoryId();
            //查询当前ID下有那些二级分类
            List<Category> secondCategoryList = list(new QueryWrapper<Category>().eq("parent_id", categoryId));

            //遍历secondCategoryList 为每个二级分类对象填充三级分类 数据
            for (Category category1 : secondCategoryList) {
                //获取二级分类Id
                Integer secId = category1.getCategoryId();
                List<Category> thirdCategoryList = list(new QueryWrapper<Category>().eq("parent_id", secId));

                //把三级分类设置到二级分类中
                category1.setCategories(thirdCategoryList);
            }

            //把查询出来的二级分类，设置到一级分类对象中
            category.setCategories(secondCategoryList);
        }

        return firstCategoryList;
    }

    @Override
    public List<Category> ccategoryRecommends() {

        final List<Category> topCategorieList = this.list(new QueryWrapper<Category>().eq("parent_id", 0));

        topCategorieList.forEach(category -> {

            final Page<Product> productPage = new Page<>(1, 6);
            productPage.addOrder(OrderItem.desc("sold_num"));

            final LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<Product>()
                    .eq(Product::getRootCategoryId, category.getCategoryId());
            iProductService.page(productPage, queryWrapper);


            final List<Product> productList = productPage.getRecords();

            if (productList!=null && productList.size()>0){

                final QueryWrapper<ProductImg> productImgQueryWrapper = new QueryWrapper<>();


                final List<String> productIdList = productList.stream().map(Product::getProductId).collect(Collectors.toList());

                productImgQueryWrapper.in("item_id",productIdList);

                final List<ProductImg> productImgsList = iProductImgService.list(productImgQueryWrapper);


                final Map<String, List<ProductImg>> productImgMap = productImgsList.stream()
                        .collect(Collectors.groupingBy(ProductImg::getItemId));


                productList.forEach(product -> {

                    List<ProductImg> productImgs = productImgMap.get(product.getProductId());
                    if (productImgs==null){
                        productImgs = new ArrayList<>();
                    }
                    product.setImgs(productImgs);

                });
            }

            category.setProducts(productList);

        });

        return topCategorieList;
    }

   /* private List<Category> organiezCategory(int i, List<Category> list) {
        Map<Integer, List<Category>> collect = list.stream().collect(Collectors
                .groupingBy(Category::getParentId));

        List<Category> list1 = collect.get(i);

        populateChildCategory(list1,collect);

        return list1;
    }

    private void populateChildCategory(List<Category> list1, Map<Integer, List<Category>> collect) {

        list1.forEach(category -> {
            List<Category> categoryList = collect.get(category.getCategoryId());
            if (categoryList != null && categoryList.size()>0){
                populateChildCategory(categoryList,collect);
            }
            category.setCategories(categoryList);
        });

    }*/

   /* private void populateChildCategory(List<Category> parentCategory, List<Category> allCategories) {
        //1. 遍历 parentCategory ，为每一个 分类信息 查找 子分类信息，并挂载
        parentCategory.forEach(category -> {

            final Integer currentId = category.getCategoryId();

            // 查找子分类信息
            final List<Category> childCategoryList = allCategories.stream()
                    .filter(c -> c.getParentId().equals(currentId))
                    .collect(Collectors.toList());

            if ( childCategoryList.size()>0 ){
                populateChildCategory(childCategoryList,allCategories);
            }

            // 挂载
            category.setCategories(childCategoryList);
        });


    }*/
}
